import os
import sys

try:
    from paver.tasks import VERSION as _PVER
    if not _PVER >= '1.0':
        raise RuntimeError("paver version >= 1.0 required (was %s)" % _PVER)
except ImportError, e:
    raise RuntimeError("paver version >= 1.0 required")
from paver.easy import *
from paver.setuputils import setup
import paver.doctools

# Configuration for distutils
setup(name = "UjU",
      version = "0.1",
      #author = "Adolfo Garcia",
      #author = "Wei-Chih,Lu",
      #author = "Matt Tierney",
      #maintainer_email = "adolfo.garcia@came.org.mx",
      description = "Provides tools to execute commands sent via SMS through a gateway.",
      long_description = ("""Application and libraries that work as bridge between an SMS gateway
              like Gammu or Kannel and a server that performs the commands specified in the
              messages. As of this version, the server is a database where the delivered data
              is stored."""),
      #url = "http://www.came.org",
      requires = ["pyodbc (>=2.1.7)",
                  "MySQLdb (>=1.2.3)"], # MySQL-python (>=1.2.3)
      package_dir = {"" : "src"},
      packages = ["uju"],
      # FIXME - Note: sdist and bdist_wininst are not including package_data in Windows!
      #package_data={'mx.org.came.Schema': ['MicroLoan/*.XML', "Microloan/Forms/*.XML"]},
      platforms = ["Linux"],
      )

# Configuration for Sphinx.
options(
    sphinx=Bunch(
        docroot="docs",
        builddir="_build"
    )
)

# Some constants that define paths
# TODO - Place the data in the options object.
PROJECT_PATH = path(__file__).abspath().dirname()
SOURCE_PATH = PROJECT_PATH / "src"
TARGET_PATH = PROJECT_PATH / "target"
TARGET_TEST_PATH = TARGET_PATH / "test" # Used to store temporary data generated by the tests
TARGET_DOCS_PATH = TARGET_PATH / "docs"
TARGET_API_DOCS_PATH = TARGET_PATH / "docs" / "html" / "api"
TARGET_CODE_COVERAGE_PATH = TARGET_DOCS_PATH / "html" / "coverage"
TARGET_PYLINT_PATH = TARGET_DOCS_PATH / "html" / "pylint"
DISTRIBUTION_PATH = PROJECT_PATH / "dist"

# Put the source directory in PYTHONPATH so it can be loaded by Sphinx & Epydoc
import sys
sys.path.append(str(SOURCE_PATH))

# FIXME - Nosetests and Coverage have problems in their current windows versions
# http://code.google.com/p/python-nose/issues/detail?id=346
@task
@needs("clean_nosetests")
def nosetests():
    """Run the unit tests and generate code coverage reports using nose."""
    TARGET_TEST_PATH.makedirs()
    nose_options = (" --with-coverage" + 
                    " --cover-package " + "mx" +
                    " --cover-html" + 
                    " --cover-html-dir=" + "\"" + TARGET_CODE_COVERAGE_PATH + "\""
                    " -w " + "\"" + SOURCE_PATH + "\"")
    sh('nosetests %s' % nose_options)

@task
def clean_nosetests():
    """Deletes all compiled files in the source directory, removes the
    'target' directory and previously generated code coverage information."""
    TARGET_TEST_PATH.rmtree()
    if PROJECT_PATH.files(".coverage") :
        os.remove(PROJECT_PATH.files(".coverage")[0])

@task
def epydoc():
    """Generates the API documentation with Epydoc"""
    from epydoc import cli
    options, names = cli.parse_arguments()
    options.target = TARGET_API_DOCS_PATH
    options.target.makedirs()
    options.target.rmtree()
    options.verbosity = 1
    # Commented out due to a bug in epydoc
#    options.docformat = "restructuredtext" 
    cli.main(options, ['mx'])

@task
def pylint():
    """Generates the Pylint report"""
    from pylint import lint
    # Files should be written to TARGET_PYLINT_PATH and Pylint only writes to the
    # current working directory.
    TARGET_PYLINT_PATH.makedirs()
    os.chdir(SOURCE_PATH)
    try:
        lint.Run(["--output-format=html", "--files-output=y", "mx/"])
    except SystemExit, exc:
        return_code = exc.args[0]
        if not (return_code == 0):
            print "WARNING: PyLint finished with a non-zero exit code:"\
                    , return_code
    finally:
	os.chdir(TARGET_PYLINT_PATH)
	MVCMD='mv {0}/pylint* ./'.format(SOURCE_PATH)
	print MVCMD
	os.popen(MVCMD)
        os.chdir(PROJECT_PATH) # Change the working directory back to the project's root


@task
@needs("nosetests")
def test():
    """Run all the tests available for the project."""

@task
@needs('paver.doctools.html')
def html():
    """Build HTML documentation using Sphinx"""
    builtdocs = path(options.sphinx.docroot) / options.sphinx.builddir / "html"
    destdir = TARGET_DOCS_PATH / "html"
    destdir.rmtree()
    builtdocs.move(destdir)

@task
@needs("nosetests")
@needs("pylint")
@needs("html")
def docs():
    """Generate Sphinx, Coverage and Epydoc documentation.
    Note: epydoc should be run separately if you want that documentation too."""

@task
@needs("clean_nosetests")
def clean():
    """Deletes all compiled files in the source directory, removes the
    'target' directory and previously generated code coverage information."""
    for file in SOURCE_PATH.walkfiles('*.pyc') :
        os.remove(file)
    if PROJECT_PATH.files(".coverage") :
        os.remove(PROJECT_PATH.files(".coverage")[0])
    TARGET_PATH.rmtree()
    DISTRIBUTION_PATH.rmtree()

